import { ElMessage } from 'element-plus'

// 常量定义（避免硬编码）
const STORAGE_KEYS = {
    TOKEN: 'blog_token',
    USER_INFO: 'userInfo',
    MSG_TIMESTAMP: 'ajax_oldTime'
}

const ERROR_MESSAGES = {
    401: (msg) => msg || '未经授权的访问',
    403: '禁止访问',
    404: '网络请求不存在',
    500: '服务器内部错误',
    502: '网关错误',
    503: '服务不可用',
    504: '网关超时',
    default: '网络连接异常'
}

// 错误消息限流（添加安全校验）
export function sendOut(msg) {
    if (!msg || typeof msg !== 'string') return

    try {
        const now = Date.now()
        const lastTime = parseInt(localStorage.getItem(STORAGE_KEYS.MSG_TIMESTAMP)) || 0

        if (!lastTime || (now - lastTime) > 3000) {
            ElMessage.error(msg)
            localStorage.setItem(STORAGE_KEYS.MSG_TIMESTAMP, now.toString())
        }
    } catch (e) {
        console.error('Error in sendOut:', e)
    }
}

// URL处理函数（增强安全性）
export const objectFormatKeysJoinUrl = (data, url) => {
    if (!url || typeof url !== 'string') return ''
    const value = Object.values(data)?.[0]
    return value ? `${url}/${encodeURIComponent(value)}` : url
}

export const objectFormatJoinUrl = (data = {}, url = '') => {
    const params = Object.entries(data)
        .filter(([_, v]) => v !== undefined && v !== null)
        .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
        .join('&')

    if (!params) return url

    return `${url}${url.includes('?') ? '&' : '?'}${params}`
}

// 文件下载处理（增强错误处理）
export function downloadFile(filename, content) {
    if (!filename || !content) {
        console.error('Invalid download parameters')
        return
    }

    try {
        const blob = new Blob([content], { type: 'application/octet-stream' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')

        a.href = url
        a.download = sanitizeFilename(filename)
        a.rel = 'noopener noreferrer'
        a.target = '_blank'

        document.body.appendChild(a)
        a.click()

        setTimeout(() => {
            document.body.removeChild(a)
            URL.revokeObjectURL(url)
        }, 100)
    } catch (e) {
        console.error('Download failed:', e)
        sendOut('文件下载失败')
    }
}

// 文件名安全处理
function sanitizeFilename(name) {
    return name.replace(/[\\/:"*?<>|]/g, '_').substring(0, 255)
}

// 文件名提取（增强健壮性）
export const fileNameFromHeader = (disposition, type) => {
    if (!disposition) return 'unknown_file'

    try {
        if (type === 1) {
            // 从URL中提取文件名
            const url = new URL(disposition.startsWith('http') ? disposition : `https://${disposition}`)
            return url.pathname.split('/').pop() || 'download'
        }
        // 处理OSS域名
        return disposition.split('.com')[0] + '.com'
    } catch (e) {
        console.warn('Filename extraction failed:', e)
        return 'download'
    }
}

// FormData处理（添加类型检查）
export const formatFormData = (data = {}) => {
    const formData = new FormData()

    Object.entries(data).forEach(([k, v]) => {
        if (v !== undefined && v !== null) {
            formData.append(k, v instanceof Blob ? v : String(v))
        }
    })

    return formData
}

// 响应处理（增强安全校验）
export function catchAjaxResolve(response) {
    if (!response?.status) {
        console.error('Invalid response object:', response)
        return Promise.reject(new Error('Invalid response'))
    }

    // 处理非200状态码
    if (response.status !== 200) {
        return Promise.resolve(response.data || {})
    }

    // 校验response.data结构
    if (!response.data || typeof response.data !== 'object') {
        console.warn('Unexpected response format:', response.data)
        return Promise.resolve(response.data || {})
    }

    const { code, msg } = response.data
    const statusCode = parseInt(code) || 0

    if (statusCode === 401) {
        handleUnauthorized(msg)
        return Promise.reject(new Error(msg || 'Unauthorized'))
    }

    if (statusCode !== 200 && msg) {
        sendOut(msg)
        return Promise.reject(new Error(msg))
    }

    return Promise.resolve(response.data)
}

// 错误处理（增强错误分类）
export function catchAjaxReject(error) {
    if (!error) {
        return Promise.reject(new Error('Unknown error occurred'))
    }

    // 请求被取消的情况
    if (Axios.isCancel(error)) {
        return Promise.reject(new Error('Request canceled'))
    }

    // 无响应的情况（网络错误）
    if (!error.response) {
        const message = navigator.onLine ? '网络连接失败' : '网络已断开'
        sendOut(message)
        return Promise.reject(new Error(message))
    }

    const { status, data } = error.response
    const errorMessage = typeof ERROR_MESSAGES[status] === 'function'
        ? ERROR_MESSAGES[status](data?.msg)
        : ERROR_MESSAGES[status] || ERROR_MESSAGES.default

    sendOut(errorMessage)

    if (status === 401) {
        handleUnauthorized(data?.msg)
    }

    return Promise.reject({
        status,
        message: errorMessage,
        data: data || {}
    })
}

// 401处理（增强安全性）
function handleUnauthorized(msg) {
    try {
        // 清除敏感信息
        [STORAGE_KEYS.TOKEN, STORAGE_KEYS.USER_INFO].forEach(key => {
            localStorage.removeItem(key)
        })

        sendOut(msg || '您的会话已过期，请重新登录')

        // 安全跳转
        setTimeout(() => {
            const redirectUrl = window.location.pathname !== '/'
                ? `/?redirect=${encodeURIComponent(window.location.pathname)}`
                : '/'
            window.location.href = redirectUrl
        }, 1500)
    } catch (e) {
        console.error('Unauthorized handling failed:', e)
        window.location.href = '/'
    }
}